<?php

// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2030 http://www.jmzh1688.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: lxl
// | jmzhfsauto
// +----------------------------------------------------------------------


namespace app\admin\controller;

use think\Controller;
use think\Db;

use app\admin\model\ProjectcontractModel;
use app\admin\model\ContracttypeModel;


class Projectcontract extends Base
{
    public function phpword(){
        $id = input('param.id');
        $res =(new ProjectcontractModel)->get($id)->toArray();
        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('static/admin/template/ht.docx');
        if(isset($res['end_time'])){
            $start_time = '';
            $end_time = '';
            foreach ($res as $key => $value){
                if($key == 'start_time'){
                    $start_time = $value;
                    $templateProcessor->setValue('contract_time_start',date('Y年m月d日',strtotime($value)));
                }
                if($key == 'end_time'){
                    $end_time = $value;
                    $templateProcessor->setValue('contract_time_end',date('Y年m月d日',strtotime($value)));
                }
            }

            $diff_time = get_weekend_days($start_time,$end_time);
            $work_day = $diff_time['total_days']-$diff_time['total_relax'];
            $templateProcessor->setValue('work_day',$work_day);

        }

        if(isset($res['oa_contract_type_id']) && !empty($res['oa_contract_type_id'])){
            $contracttype_res = (new ContracttypeModel)->get($res['oa_contract_type_id'])->toArray();
        }

        if(isset($contracttype_res['name']) && !empty($contracttype_res['name'])){
            $payment_type = $contracttype_res['name'];
        }else{
            $payment_type = '343';
        }


        switch ($payment_type){
            case '343':
                $first_phase = $res['price']*0.3;
                $chinese_number_first_phase = toChineseNumber($first_phase);
                $second_phase = $res['price']*0.4;
                $chinese_number_second_phase = toChineseNumber($second_phase);
                $third_phase = $res['price']*0.3;
                $chinese_number_third_phase = toChineseNumber($third_phase);
                $templateProcessor->setValue('first_phase',$first_phase);
                $templateProcessor->setValue('first_percent',30);
                $templateProcessor->setValue('chinese_number_first_phase',$chinese_number_first_phase);
                $templateProcessor->setValue('second_phase',$second_phase);
                $templateProcessor->setValue('second_percent',40);
                $templateProcessor->setValue('chinese_number_second_phase',$chinese_number_second_phase);
                $templateProcessor->setValue('third_phase',$third_phase);
                $templateProcessor->setValue('third_percent',30);
                $templateProcessor->setValue('chinese_number_third_phase',$chinese_number_third_phase);

            case '442':
                $first_phase = $res['price']*0.4;
                $chinese_number_first_phase = toChineseNumber($first_phase);
                $second_phase = $res['price']*0.4;
                $chinese_number_second_phase = toChineseNumber($second_phase);
                $third_phase = $res['price']*0.2;
                $chinese_number_third_phase = toChineseNumber($third_phase);
                $templateProcessor->setValue('first_phase',$first_phase);
                $templateProcessor->setValue('first_percent',40);
                $templateProcessor->setValue('chinese_number_first_phase',$chinese_number_first_phase);
                $templateProcessor->setValue('second_phase',$second_phase);
                $templateProcessor->setValue('second_percent',40);
                $templateProcessor->setValue('chinese_number_second_phase',$chinese_number_second_phase);
                $templateProcessor->setValue('third_phase',$third_phase);
                $templateProcessor->setValue('third_percent',20);
                $templateProcessor->setValue('chinese_number_third_phase',$chinese_number_third_phase);
        }
        $chinese_number_price = toChineseNumber($res['price']);
        $templateProcessor->setValue('chinese_number_price',$chinese_number_price);
        $templateProcessor->setValue('price',$res['price']);
        $templateProcessor->setValue('projec_title',$res['projec_title']);
        $templateProcessor->setValue('code',$res['code']);
        $templateProcessor->setValue('party_a',$res['party_a']);
        $templateProcessor->setValue('party_b',$res['party_b']);
        $templateProcessor->setValue('party_b_bank_account',$res['party_b_bank_account']);
        $templateProcessor->setValue('party_b_bank_address',$res['party_b_bank_address']);
        $templateProcessor->setValue('party_b_credit_code',$res['party_b_credit_code']);
        $templateProcessor->setValue('payment_type',$payment_type);

        $path = $templateProcessor->save(ROOT_PATH .'/static/admin/template/ht.docx');
        // 下载文件到浏览器
        if (!file_exists($path)){
            echo  "没有该文件";
            return;
        }else{
            ob_clean();
            ob_start();
            $filename = $res['projec_title'] .'.doc';
            $fp = fopen($path, "r");
            $file_size = filesize($path);
            Header("Content-type:  application/octet-stream ");
            Header("Accept-Ranges:  bytes ");
            Header("Accept-Length:".$file_size);
            Header("Content-Disposition:  attachment;  filename= $filename");
            $buffer=1024;
            $file_count=0;
            $file  = fopen($path, "r");
            while (!feof($file) && $file_count<$file_size) {
                $file_con=fread($fp,$buffer);
                $file_count +=$buffer;
                echo $file_con;
            }
            fclose($fp);
            ob_end_flush();
        }

        /*$section = $phpWord->addSection();
        $fontStyle = [
            'name' => 'Microsoft Yahei UI',
            'size' => 20,
            'color' => '#ff6600',
            'bold' => true
        ];
        $textrun = $section->addTextRun();
        $textrun->addText('功能模块 ', $fontStyle);*/
        //$section->addLink('https://www.helloweba.net', '欢迎访问Helloweba', array('color' => '0000FF', 'underline' => \PhpOffice\PhpWord\Style\Font::UNDERLINE_SINGLE));
        //$section->addTextBreak();

// Write some text
        //$section->addTextBreak();
        //$section->addText('Some text...');

// Image
        //$section->addImage('logo.png', array('width'=>64, 'height'=>64));

// 页眉
        //$header = $section->addHeader();
//$header->addText('Subsequent pages in Section 1 will Have this!');
        //$header->addImage('logo.png', array('width' => 16, 'height' => 16, 'alignment' => \PhpOffice\PhpWord\SimpleType\Jc::RIGHT));

// 页脚
        //$footer = $section->addFooter();
        //$footer->addPreserveText('Page {PAGE} of {NUMPAGES}.', null, array('alignment' => \PhpOffice\PhpWord\SimpleType\Jc::CENTER));
//$footer->addLink('https://github.com/PHPOffice/PHPWord', 'PHPWord on GitHub');

// 增加一页
        //$section = $phpWord->addSection();
        //$section->addText('This section uses other margins with folio papersize.');



        //$header = array('size' => 16, 'bold' => true);

// table
        //$rows = 10;
        //$cols = 5;
        //$section->addText('Basic table', $header);

        /*$table = $section->addTable();
        for ($r = 1; $r <= 8; $r++) {
            $table->addRow();
            for ($c = 1; $c <= 5; $c++) {
                $table->addCell(1750)->addText("Row {$r}, Cell {$c}");
            }
        }*/

        //$section->addTextBreak(1);
        //$section->addText('Fancy table', $header);

        /*$fancyTableStyleName = 'Fancy Table';
        $fancyTableStyle = array('borderSize' => 6, 'borderColor' => '006699', 'cellMargin' => 80, 'alignment' => \PhpOffice\PhpWord\SimpleType\JcTable::CENTER);
        $fancyTableFirstRowStyle = array('borderBottomSize' => 18, 'borderBottomColor' => '0000FF', 'bgColor' => '66BBFF');
        $fancyTableCellStyle = array('valign' => 'center');
        $fancyTableCellBtlrStyle = array('valign' => 'center', 'textDirection' => \PhpOffice\PhpWord\Style\Cell::TEXT_DIR_BTLR);
        $fancyTableFontStyle = array('bold' => true);
        $phpWord->addTableStyle($fancyTableStyleName, $fancyTableStyle, $fancyTableFirstRowStyle);
        $table = $section->addTable($fancyTableStyleName);
        $table->addRow(900);
        $table->addCell(2000, $fancyTableCellStyle)->addText('模块', $fancyTableFontStyle);
        $table->addCell(2000, $fancyTableCellStyle)->addText('功能', $fancyTableFontStyle);
        $table->addCell(2000, $fancyTableCellStyle)->addText('金额', $fancyTableFontStyle);
        $table->addCell(2000, $fancyTableCellStyle)->addText('', $fancyTableFontStyle);
        $table->addCell(2000, $fancyTableCellStyle)->addText('', $fancyTableFontStyle);
        $table->addCell(2000, $fancyTableCellStyle)->addText('', $fancyTableFontStyle);
        //$table->addCell(500, $fancyTableCellBtlrStyle)->addText('Row 5', $fancyTableFontStyle);
        //dump($mind_data['data']);
        foreach ($mind_data['data'] as $key => $value){
            if(isset($value['parentid']) && ($value['parentid'] != 'root')) {
                $table->addRow();
                foreach ($mind_data['data'] as $key1 => $value1) {
                    if ($value1['id'] == $value['parentid']) {
                        $table->addCell(2000)->addText($value1['topic']);
                        break;
                    }
                }
                $table->addCell(2000)->addText($value['topic']);
                $table->addCell(2000)->addText($value['price']);
                $table->addCell(2000)->addText($value['combo1']);
                $table->addCell(2000)->addText($value['combo2']);
                $table->addCell(2000)->addText($value['combo3']);
            }
        }*/
        /*for ($i = 1; $i <= 8; $i++) {
            $table->addRow();
            $table->addCell(2000)->addText("Cell {$i}");
            $table->addCell(2000)->addText("Cell {$i}");
            $table->addCell(2000)->addText("Cell {$i}");
            //$table->addCell(2000)->addText("Cell {$i}");
            $text = (0 == $i % 2) ? 'X' : '';
            $table->addCell(500)->addText($text);
        }*/
        /*$file = 'test.docx';
        if(ob_get_length()) ob_end_clean();
        header("Content-Description: File Transfer");
        header('Content-Disposition: attachment; filename="' . $file . '"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
        header('Content-Transfer-Encoding: binary');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Expires: 0');
        ob_start(); //打开缓冲区
        $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $xmlWriter->save("php://output",'Word2007',true);*/
    }


    public function getWhereFromPara()
    {
        $param = input('param.');
        $where=[];

        
        if(array_key_exists('',$param)) {$where['']=$param[''];}  
        

        return $where;
    }


    
    public function _initialize()
    {
        $wherep=$this->getWhereFromPara();
        $furl=url('projectcontract/index' ,$wherep);
        $faddurl=url('projectcontract/add' ,$wherep);
        $fediturl=url('projectcontract/edit' ,$wherep);
        
        $projectcontractmodel = new ProjectcontractModel();
        $tabblename = $projectcontractmodel->getTable();//获取表
        
        $this->assign([
            'nowurl' => $furl,
            'addurl' => $faddurl,
            'editurl'=> $fediturl,
            'tabblename' => $tabblename
        ]);
       
    }
 

    public function index()
    {

        $wherep=$this->getWhereFromPara();
    

        if(request()->isAjax()){
            $param = input('param.');
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
            $projectcontractmodel = new ProjectcontractModel();


            $where = getWhereForm( $param);
            $where['isdelete']=0;
            $whereor=[];

            
            


            $where=array_merge($where,$wherep);
    

            $list = $projectcontractmodel->getByWhere($where, $offset, $limit, $whereor);
            foreach($list as $key=>$vo){
                $list[$key]['operate'] = $this->getRowButton($vo,$wherep);
            }
          
            

            $result['total'] =$projectcontractmodel->getAllCount($where, $whereor);  // 总数据
            $result['rows'] = $list;
            return json($result);
        }
 

        $toolbarshow= $this->getToolBar($wherep);

        $this->assign([
            'toolbar' => $toolbarshow
        ]);
       

        return $this->fetch();

    }

    public function del()
    {
        $projectcontractmodel = new ProjectcontractModel();
        if(request()->isPost()){
            $id = input("post.id");
            $msg = $projectcontractmodel->delById($id);
            return json(msg($msg['code'], $msg['data'], $msg['msg']));
        }
        return $this->fetch();
    }

    public function edit()
    {
        $projectcontractmodel = new ProjectcontractModel();

        if(request()->isPost()){
            $param = input("post.");

            
 
            foreach ($param as $key=>$value){
                if(is_array($value))
                {
                    $param[$key]=implode(",",$param[$key]);
                }
            }
           
            $wherep=$this->getWhereFromPara();
            $parastr="";
            foreach ($wherep as $key => $value)
            {
                $parastr=$parastr.$key."=".$value."&";
            }


            

            $msg = $projectcontractmodel->edit($param);
            return json(msg($msg['code'], $msg['data']."?". $parastr, $msg['msg']));
        }
      
        $id = input('param.id');
        $info=$projectcontractmodel->getById($id);
  
        $this->assign([
            'info' => $info
        ]);
        return $this->fetch();
    }

    public function add()
    {
    

        if(request()->isPost()){
            $projectcontractmodel = new ProjectcontractModel();
            $param = input("post.");
            $wherep=$this->getWhereFromPara();
            $param=array_merge($param,$wherep);

           
            $parastr="";
            foreach ($wherep as $key => $value)
            {
                $parastr=$parastr.$key."=".$value."&";
            }

			
			
			
			foreach ($param as $key=>$value){
                if(is_array($value))
                {
                    $param[$key]=implode(",",$param[$key]);
                }
            }
			
			
			
            
            

            

            $msg = $projectcontractmodel->add($param);
            return json(msg($msg['code'], $msg['data']."?". $parastr, $msg['msg']));
        }
    
        return $this->fetch();
    }



  
        private function getRowButton($vo,$wherep)
        {
           
            $id=$vo['id'];
            
            $idwhere=$wherep;

            $idwhere['id']=$id;

     
         
            $operatestr='[{"uuid":"edit","title":"编辑","href":"'.url('edit', ['id' => $id]).'","icon":"","style":"","para":"","isblank":"0","isnouse":0},{"uuid":"del","title":"删除","href":"javascript:del(this,$id)","icon":"","style":"","para":"","isblank":"0","isnouse":0},{"uuid":"guidb36c80","title":"生成word","href":"'.url('phpword', ['id' => $id]).'","icon":"","style":"","para":"","isblank":"0","isnouse":0}]';

            $arr=$vo->toArray();
            foreach ($arr as $key => $value)
            {
                $operatestr=str_replace("$".$key,$value, $operatestr);
            }

               $operate=json_decode($operatestr,true);
              $option= getButtonHtml($operate);
                return $option;
    
        }


        private function getToolBar($where)
        {
           
          
            $operatestr='[{"uuid":"add","title":"添加","href":"'.url('add' ,$where).'","icon":"","style":"btn btn-outline-primary btn-sm ","para":"","isblank":"0","isnouse":0}]';
               foreach ($where as $key => $value)
               {
                   $operatestr=str_replace("$".$key,$value, $operatestr);
               }
             

               $operate=json_decode($operatestr,true);
              $option= getButtonHtml($operate);
                return $option;
    
        }
        
        /**/
    
}
